{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Copyright 2014 Brett Slatkin, Pearson Education Inc.\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "# Preamble to mimick book environment\n",
    "import logging\n",
    "from pprint import pprint\n",
    "from sys import stdout as STDOUT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(<class '__main__.Meta'>,\n",
      " 'MyClass',\n",
      " (<class 'object'>,),\n",
      " {'__module__': '__main__',\n",
      "  '__qualname__': 'MyClass',\n",
      "  'foo': <function MyClass.foo at 0x103e5d158>,\n",
      "  'stuff': 123})\n"
     ]
    }
   ],
   "source": [
    "# Example 1\n",
    "class Meta(type):\n",
    "    def __new__(meta, name, bases, class_dict):\n",
    "        orig_print = __builtins__.print\n",
    "        print = pprint\n",
    "        print((meta, name, bases, class_dict))\n",
    "        print = orig_print\n",
    "        return type.__new__(meta, name, bases, class_dict)\n",
    "\n",
    "class MyClass(object, metaclass=Meta):\n",
    "    stuff = 123\n",
    "\n",
    "    def foo(self):\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 2\n",
    "class Meta(type):\n",
    "    def __new__(meta, name, bases, class_dict):\n",
    "        print(meta, name, bases, class_dict)\n",
    "        return type.__new__(meta, name, bases, class_dict)\n",
    "\n",
    "class MyClassInPython2(object):\n",
    "    __metaclass__ = Meta\n",
    "    stuff = 123\n",
    "\n",
    "    def foo(self):\n",
    "        pass\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "180\n"
     ]
    }
   ],
   "source": [
    "# Example 3\n",
    "class ValidatePolygon(type):\n",
    "    def __new__(meta, name, bases, class_dict):\n",
    "        # Don't validate the abstract Polygon class\n",
    "        if bases != (object,):\n",
    "            if class_dict['sides'] < 3:\n",
    "                raise ValueError('Polygons need 3+ sides')\n",
    "        return type.__new__(meta, name, bases, class_dict)\n",
    "\n",
    "class Polygon(object, metaclass=ValidatePolygon):\n",
    "    sides = None  # Specified by subclasses\n",
    "\n",
    "    @classmethod\n",
    "    def interior_angles(cls):\n",
    "        return (cls.sides - 2) * 180\n",
    "\n",
    "class Triangle(Polygon):\n",
    "    sides = 3\n",
    "\n",
    "print(Triangle.interior_angles())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before class\n",
      "Before sides\n",
      "After sides\n"
     ]
    }
   ],
   "source": [
    "# Example 4\n",
    "try:\n",
    "    print('Before class')\n",
    "    class Line(Polygon):\n",
    "        print('Before sides')\n",
    "        sides = 1\n",
    "        print('After sides')\n",
    "    print('After class')\n",
    "except:\n",
    "    logging.exception('Expected')\n",
    "else:\n",
    "    assert False"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
